package main

import (
	"flag"
	"fmt"
	"io"
	"net"
	"os"
)

type Client struct {
	ServerIp   string
	ServerPort int
	Name       string
	conn       net.Conn
	flag       int
}

func NewClient(serverIp string, serverPort int) *Client {
	//创建客户端对象
	client := &Client{
		ServerIp:   serverIp,
		ServerPort: serverPort,
		flag:       999,
	}

	//链接Server
	conn, err := net.Dial("tcp", fmt.Sprintf("%s:%d", serverIp, serverPort))
	if err != nil {
		fmt.Println("net.Dial error: ", err)
		return nil
	}

	client.conn = conn

	//返回对象
	return client
}

// 处理server回应的消息，直接显示到标准输出即可
func (c *Client) DealResponse() {
	//一但c.conn有数据，就直接copy到stdout标准输出上，永久阻塞监听
	io.Copy(os.Stdout, c.conn)
}

func (c *Client) menu() bool {
	var flag int

	fmt.Println("1.Public chat mode")
	fmt.Println("2.Private chat mode")
	fmt.Println("3.Update user name")
	fmt.Println("0.exit")

	fmt.Scanln(&flag)

	if flag >= 0 && flag <= 3 {
		c.flag = flag
		return true
	} else {
		fmt.Println(">>>>Please enter a number within the legal range<<<<")
		return false
	}
}

func (c *Client) UpdateName() bool {

	fmt.Println("Please enter username")
	fmt.Scanln(&c.Name)

	sendMsg := "rename|" + c.Name + "\n"
	_, err := c.conn.Write([]byte(sendMsg))
	if err != nil {
		fmt.Println("net.conn write error: ", err)
		return false
	}

	return true
}

func (c *Client) PublicChat() {
	//提示用户输入消息
	var chatMsg string

	fmt.Println("Please enter message,enter \"exit\" is exit.")
	fmt.Scanln(&chatMsg)

	for chatMsg != "exit" {
		//发送给服务器

		//消息不为空则发送
		if len(chatMsg) != 0 {
			sendMsg := chatMsg + "\n"
			_, err := c.conn.Write([]byte(sendMsg))
			if err != nil {
				fmt.Println("net.conn Write error: ", err)
				break
			}
		}
		chatMsg = ""
		fmt.Println(">>>>Please enter message,enter \"exit\" is exit.")
		fmt.Scanln(&chatMsg)
	}
}

// 查询在线用户
func (c *Client) SelectUsers() {
	sendMsg := "/who\n"
	_, err := c.conn.Write([]byte(sendMsg))
	if err != nil {
		fmt.Println("net.conn Write error: ", err)
		return
	}
}

// 私聊模式
func (c *Client) PrivateChat() {
	var remoteName string
	var chatMsg string

	c.SelectUsers()
	fmt.Println(">>>>Please enter the user name of the person you are chatting with,enter \"exit\" is exit.")
	fmt.Scanln(&remoteName)

	for remoteName != "exit" {
		fmt.Println(">>>>Please enter message,enter \"exit\" is exit.")
		fmt.Scanln(&chatMsg)

		for chatMsg != "exit" {
			//消息不为空则发送
			if len(chatMsg) != 0 {

				sendMsg := "to|" + remoteName + "|" + chatMsg + "\n\n"

				_, err := c.conn.Write([]byte(sendMsg))
				if err != nil {
					fmt.Println("net.conn Write error: ", err)
					break
				}
			}
			chatMsg = ""
			fmt.Println(">>>>Please enter message,enter \"exit\" is exit.")
			fmt.Scanln(&chatMsg)
		}
		c.SelectUsers()
		fmt.Println(">>>>Please enter the user name of the person you are chatting with,enter \"exit\" is exit.")
		fmt.Scanln(&remoteName)
	}
}

func (c *Client) Run() {
	for c.flag != 0 {
		for c.menu() != true {
		}

		//根据不同模式处理不同业务
		switch c.flag {
		case 1:
			//公聊模式
			c.PublicChat()
		case 2:
			//私聊模式
			c.PrivateChat()
		case 3:
			//更新用户名
			c.UpdateName()

		}
	}

}

var serverIp string
var serverPort int

func init() {
	flag.StringVar(&serverIp, "ip", "127.0.0.1", "设置服务器IP地址(默认是127.0.0.1)")
	flag.IntVar(&serverPort, "port", 8888, "设置服务器端口(默认是8888)")
}

func main() {
	//命令行解析
	flag.Parse()

	client := NewClient(serverIp, serverPort)
	if client == nil {
		fmt.Println(">>>>>>>>Failed to connect to server.exe...")
		return
	}

	//单独开启一个goroutine去处理server的回执消息
	go client.DealResponse()

	fmt.Println(">>>>>>>>Successfully connecting to the server.exe...")

	//启动客户端业务
	client.Run()
}
